package com.fch.loadlib;


import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;


public class ProDownLoad {
    private List<String> lanZipList = new ArrayList<>();
    private List<String> localList = new ArrayList<>();
    private String rootFolderUrl, installFolderUrl, assetsFolderUrl;
    Context context;

    public ProDownLoad(Context context) {
        this.context = context;
    }

    //开始下载逻辑
    public void StartLoad() {
        CreateFile();
    }

    // 创建文件
    public void CreateFile() {
        String rootFolderName = "CreateParty";
        String installFolderName = "Install";
        String assetsFolderName = "Assets";
        String fileName = "config.txt";

        // 获取外部存储的根目录  /storage/emulated/0
        File rootDir = Environment.getExternalStorageDirectory();
        File rootFile = new File(rootDir, rootFolderName);
        File installFile = new File(rootFile, installFolderName);
        File assetsFile = new File(rootFile, assetsFolderName);

        rootFolderUrl = rootFile.getPath();
        installFolderUrl = installFile.getPath();
        assetsFolderUrl = assetsFile.getPath();

        if (!installFile.exists()) {
            installFile.mkdirs();
        }
        if (!assetsFile.exists()) {
            assetsFile.mkdirs();
        }

        Log.d("创建rootFile文件夹的路径:", rootFile.getPath());
        Log.d("创建installFile文件夹的路径:", installFile.getPath());
        Log.d("创建assetsFile文件夹的路径:", assetsFile.getPath());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    LoadApk();

                }
            }).start();
        }
    }

    //局域网查询
    public void LANInquire() {

        try {
            InquireAssetFolder();
            InquireLocalAssetFolder();

            Thread.sleep(500);

            //AssetsPackageCompress();

            if (IsAssetsLoad()) {
                Log.d("更新查询", "无需更新");
            } else {
                Log.d("更新查询", "需要更新");
                LoadZip();
                //LoadZipUseJCIFS();
            }
        } catch (Exception e) {
            Log.e("查询错误", e.toString());
        }
    }

    //局域网文件目录查询
    public void InquireAssetFolder() {

        String sourcePath = "http://192.168.21.200:90/UnityAssets/CreatParty/StreamingAssets";

        try {
            String host = "192.168.21.200"; //共享文件夹所在的主机IP地址
            String url = "smb://" + host + "/UnityAssets/CreatParty/StreamingAssets/"; //共享文件夹的URL地址
            String username = "Program"; //共享文件夹的用户名
            String password = "Program"; //共享文件夹的密码

            //使用SMB协议连接共享文件夹
            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("", username, password);
            SmbFile smbFile = new SmbFile(url, auth);

            //列出共享文件夹中的所有文件和文件夹
            SmbFile[] files = smbFile.listFiles();
            for (SmbFile file : files) {
                Log.i("File Name", file.getName());
                lanZipList.add(file.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //本地资源目录查询
    public void InquireLocalAssetFolder() {
        String folderPath = assetsFolderUrl;
        File folder = new File(folderPath);
        if (folder.exists() && folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    Log.d("", file.getName());
                    localList.add(file.getName());
                }
            }
        }
    }

    public boolean IsAssetsLoad() {

        int passCount = 0;

        for (int i = 0; i < lanZipList.size(); i++) {
            for (int j = 0; j < localList.size(); j++) {

                if (lanZipList.get(i).contains(localList.get(j))) {
                    passCount++;
                    break;
                }
            }
        }

        return passCount == lanZipList.size();
    }

    public void LoadZip() {

        Log.d("开始下载资源包", "True");

        String lanAssetsRoot = "http://192.168.21.200:90/UnityAssets/CreatParty/StreamingAssets/";
        String fileName = assetsFolderUrl + "/";

        HttpURLConnection connection = null;
        FileOutputStream outputStream = null;
        InputStream inputStream = null;

        try {

            for (int i = 0; i < lanZipList.size(); i++) {

                URL downloadUrl = new URL(lanAssetsRoot + lanZipList.get(i));
                connection = (HttpURLConnection) downloadUrl.openConnection();
                connection.setRequestMethod("GET");
                connection.setRequestProperty("Accept-Encoding", "identity");
//                connection.setDoInput(true);
                connection.connect();

                int fileLength = connection.getContentLength();

                Log.d("文件长度:", "" + fileLength);

                inputStream = connection.getInputStream();
                outputStream = new FileOutputStream(fileName + lanZipList.get(i));

                byte[] buffer = new byte[4096];
                int allLength = 0;
                int bytesRead = 0;
                while ((bytesRead = inputStream.read(buffer)) != -1) {

                    allLength += bytesRead;
//                  Log.d("", "" + (float) allLength / fileLength);
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();


                Log.e("fileLength", "" + fileLength);
                Log.e("allLength", "" + allLength);
            }

            outputStream.close();
            inputStream.close();
            connection.disconnect();

            Log.d("下载完成", "");

        } catch (Exception e) {
            e.printStackTrace();
        }

        Log.d("", "资源包下载完成！");

        AssetsPackageCompress();
    }

    //使用JCIFS来下载资源
    public void LoadZipUseJCIFS() {

        String host = "192.168.21.200"; //共享文件夹所在的主机IP地址
        String url = "smb://" + host + "/UnityAssets/CreatParty/StreamingAssets/";

        String fileName = assetsFolderUrl + "/";

        InputStream in = null;
        FileOutputStream out = null;
        try {
            for (int i = 0; i < lanZipList.size(); i++) {

                NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("", "Program", "Program");
                SmbFile remoteFile = new SmbFile(url + lanZipList.get(i), auth);
                remoteFile.connect(); //尝试连接

                in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
                out = new FileOutputStream(fileName + lanZipList.get(i));

                int allLength = 0;
                int fileLength = remoteFile.getContentLength();

                //读取文件内容
                byte[] buffer = new byte[4096];
                int len = 0; //Read length
                while ((len = in.read(buffer, 0, buffer.length)) != -1) {
                    allLength += len;
                    out.write(buffer, 0, len);
                    Log.d("", "" + (float) allLength / fileLength);
                }
                out.flush(); //方法刷新此输出流并强制将所有缓冲的输出字节被写出
            }
        } catch (Exception e) {
            String msg = "Download a remote file error: " + e.getLocalizedMessage();
            System.out.println(msg);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                Log.d("LoadZipUseJCIFS", "下载完成！");
            } catch (Exception e) {
            }
        }


    }

    public  void Install2OpenApk(){

        File apkFile = new File("/storage/emulated/0/CreateParty/Install/CreateParty.apk");
        Uri apkUri =  FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".fileprovider", apkFile);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        context.startActivity(intent);
    }

    //解压
    public void AssetsPackageCompress() {

        int BUFFER_SIZE = 4096;

        File destDir = new File(assetsFolderUrl + "/");

        byte[] buffer = new byte[BUFFER_SIZE];

        try {

            for (int i = 0; i < lanZipList.size(); i++) {

                ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(assetsFolderUrl + "/" + lanZipList.get(i)));

                ZipEntry zipEntry = zipInputStream.getNextEntry();

                Log.d("zipEntry.getName", zipEntry.getName());

                while (zipEntry != null) {
                    String fileName = zipEntry.getName();
                    File newFile = new File(destDir, fileName);

                    if (zipEntry.isDirectory()) {
                        newFile.mkdirs();
                    } else {
                        FileOutputStream fos = new FileOutputStream(newFile);
                        int len;
                        while ((len = zipInputStream.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                        fos.close();
                    }

                    zipEntry = zipInputStream.getNextEntry();
                }

                zipInputStream.closeEntry();
                zipInputStream.close();

                File zipFile = new File(assetsFolderUrl + "/" + lanZipList.get(i));

                if (zipFile.exists()) {
                    zipFile.delete();
                }
            }

            Log.d("", " Compress successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //下载apk
    public void LoadApk() {

        String url = "http://192.168.21.200:90/UnityAssets/CreatParty/Install/CreatParty.apk";
        String fileName = installFolderUrl + "/CreateParty.apk";

        if (new File(fileName).exists()) {
            Log.d("", "文件存在！");

            LANInquire();
            return;
        }

        try {
            URL downloadUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept-Encoding", "identity");
            connection.setDoInput(true);
            connection.connect();

            int fileLength = connection.getContentLength();

            Log.d("文件长度:", "" + fileLength);

            InputStream inputStream = connection.getInputStream();
            FileOutputStream outputStream = new FileOutputStream(fileName);

            byte[] buffer = new byte[4096];
            int allLength = 0;
            int bytesRead = 0;
            while ((bytesRead = inputStream.read(buffer)) != -1) {

                allLength += bytesRead;
                Log.d("", "" + (float) allLength / fileLength);
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            connection.disconnect();

            Log.d("下载完成", "" + allLength);

        } catch (Exception e) {
            e.printStackTrace();
        }
        LANInquire();
    }

    public String UrlChange(String url) {

        String newUrl = url.replace('\\', '/');
        newUrl = newUrl.replace("/", File.separator);
        return newUrl;
    }
}
